package com.infotech.NginxMonitor.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetworkInfo {
	private static int receiveRate;	// unit: byte
	private static int transmitRate;
	private static int receiveTotal;
	private static int transmitTotal;
	
	public void refresh() {
		String str;

		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader(new File(
					"/proc/net/dev")));
			Pattern pattern = Pattern.compile("eth0");
			while ((str = reader.readLine()) != null) {
				Matcher matcher = pattern.matcher(str);
				if (matcher.find()) {
					String[] array = str.split("\\s+");
					
					receiveRate = Integer.parseInt(array[1]) - receiveTotal;
					transmitRate = Integer.parseInt(array[9]) - transmitTotal;
					
					receiveTotal = Integer.parseInt(array[1]);
					transmitTotal = Integer.parseInt(array[9]);
					
					break;
				}
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public int getTransmitRate() {
		return transmitRate;
	}

	public void setTransmitRate(int transmitRate) {
		NetworkInfo.transmitRate = transmitRate;
	}

	public int getReceiveRate() {
		return receiveRate;
	}

	public void setReceiveRate(int receiveRate) {
		NetworkInfo.receiveRate = receiveRate;
	}
}
